#include "GraphNodeItem.h"
#include "Arrow.h"
#include "../GraphScene.h"
#include "ContextMenuManager.h"
#include <QtGui>

GraphNodeItem::GraphNodeItem(GraphScene *scene) : _scene(scene)
{
	_deleted = false;

	setFont(QFont(font().family(), 12));
	setDefaultTextColor(Qt::white);

	setFlag(QGraphicsItem::ItemIsMovable);
	setFlag(QGraphicsItem::ItemIsSelectable);
	setTextInteractionFlags(Qt::NoTextInteraction);
}

GraphNodeItem::~GraphNodeItem()
{
	_deleted = true;
	qDeleteAll(_arrows);
}

void GraphNodeItem::addArrow(Arrow *arrow)
{
	_arrows.insert(arrow);
}

void GraphNodeItem::deleteArrow(Arrow *arrow)
{
	if (!_deleted)
		_arrows.remove(arrow);
}

void GraphNodeItem::focusOutEvent(QFocusEvent *event)
{
	setTextInteractionFlags(Qt::NoTextInteraction);

	QTextCursor cursor = textCursor();
	cursor.clearSelection();
	setTextCursor(cursor);
	
	QGraphicsTextItem::focusOutEvent(event);
}

void GraphNodeItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
	if (textInteractionFlags() == Qt::NoTextInteraction && _scene->mode() == GraphScene::Move)
	{
		setTextInteractionFlags(Qt::TextEditorInteraction);	
		setSelected(true);
	}
	QGraphicsTextItem::mouseDoubleClickEvent(event);
}

void GraphNodeItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
	painter->setRenderHint(QPainter::Antialiasing);

	QRectF r = boundingRect();
	QLinearGradient linearGradient(r.topLeft(), r.bottomRight());
	linearGradient.setColorAt(0.0, QColor(116,143,173));
	linearGradient.setColorAt(0.6, QColor(137,164,192));
	linearGradient.setColorAt(1.0,  QColor(144,191,148));

	QPainterPath s = shape();
	painter->fillPath(s, linearGradient);
	painter->drawPath(s);

	QGraphicsTextItem::paint(painter, option, widget);
}

QRectF GraphNodeItem::boundingRect() const
{
	QRectF r = QGraphicsTextItem::boundingRect();
	const int margin = 10;
	r.adjust(-margin, -margin, margin, margin);
	return r;
}

bool GraphNodeItem::contains(const QPointF & point) const
{
	return shape().contains(point);
}


void GraphNodeItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
	if (_scene->mode() == GraphScene::ReadOnly)
		return;

	QMenu& menu = ContextMenuManager::instance().get(ClassMenu);
	scene()->clearSelection();
	setSelected(true);
	QAction* result = menu.exec(event->screenPos());
	if (result == ContextMenuManager::instance().deleteAction())
	{
		_deleted = true;
		qDeleteAll(_arrows);
		scene()->removeItem(this);
	}
}
